package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC utilities
 *
 * @author chisheng
 */
public class JDBCUtils {

    /**
     * A factory for connections to the physical data source that this DataSource
     * object represents.
     */
    private static DataSource dataSource;

    static {
        try {
            final Properties props = new Properties();
            props.load(JDBCUtils.class.getResourceAsStream("jdbc.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get data source instance
     *
     * @return DataSource instance
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * Attempts to establish a connection with the data source that this DataSource
     * object represents.
     *
     * @return a connection to the data source
     */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // throws a exception if getConnection executed failed
        throw new RuntimeException("Failed get connection instance.");
    }

    /**
     * Close resources
     *
     * @param stmt statement
     * @param conn connection
     */
    public static void close(Statement stmt, Connection conn) {
        close(stmt, conn, null);
    }

    /**
     * Close resources
     *
     * @param stmt statement
     * @param conn connection
     * @param rs   result set
     */
    public static void close(Statement stmt, Connection conn, ResultSet rs) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
